﻿using Dyd.BaseService.ServiceCenter.Domain;
using Dyd.BaseService.ServiceCenter.Domain.Bll;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XXF.Db;

namespace Dyd.BaseService.ServiceCenter.Monitor
{
    public class MonitorTask : XXF.BaseService.TaskManager.BaseDllTask
    {
        public override void Run()
        {
            try
            {
                InitConfig();
                Do();
            }
            catch (Exception exception)
            {
                base.OpenOperator.Error("生成商家评分汇总数据失败", exception);
            }
        }

        public void InitConfig()
        {
            XXF.Common.XXFConfig.ConfigConnectString = base.AppConfig["ServiceCenterConnectString"];
        }

        private void Do()
        {
            Task task = new Task(() =>
            {
                while (true)
                {
                    using (DbConn conn = DbConfig.CreateConn(DataConfig.ServiceCenterConnectString))
                    {
                        conn.Open();
                        var list = tb_node_bll.Instance.GetTimeOutNode(conn, XXF.BaseService.ServiceCenter.SystemRuntime.SystemParamConfig.Node_HeatBeat_Time_Out);
                        var mes = string.Empty;
                        foreach (var item in list)
                        {
                            try
                            {
                                item.runstate = (int)XXF.BaseService.ServiceCenter.SystemRuntime.EnumRunState.Stop;
                                tb_node_bll.Instance.Update(conn, item);
                            }
                            catch (Exception ex)
                            {
                                XXF.Log.ErrorLog.Write(ex.Message, ex);
                            }
                            mes += item.id + ",";
                        }
                        XXF.Log.ErrorLog.Write("节点" + mes + "超时", new Exception(mes));
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(XXF.BaseService.ServiceCenter.SystemRuntime.SystemParamConfig.Node_HeatBeat_Every_Time));
                }
            });
            //"select DATEDIFF(\"MS\",nodeheartbeattime,GETDATE()), * from [tb_node] where DATEDIFF('MS',nodeheartbeattime,GETDATE())>"
        }



        public override void TestRun()
        {
            /*测试环境下任务的配置信息需要手工填写,正式环境下需要配置在任务配置中心里面*/
            base.AppConfig = new XXF.BaseService.TaskManager.SystemRuntime.TaskAppConfigInfo();
            base.AppConfig.Add("ServiceCenterConnectString", "server=192.168.17.201;Initial Catalog=dyd_bs_servicecenter_report;User ID=sa;Password=Xx~!@#;");
            base.TestRun();
        }
    }
}
